import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

/**
 * 对于请求内容返回结果不是200 的，全部报错
 */
service.interceptors.response.use(
    response => {
      //如果返回的状态 不是200,说明是错误的
      if (response.status !== 200) {
        Message({
          message: response.data || 'Error',
          type: 'error',
          duration: 3 * 1000
        })
        return Promise.reject(new Error(response.data || 'Error'))
      } else {
        // 20001 表示，执行了全局处理
        if (response.data.code === 20001) {
          Message({
            message: response.data || 'Error',
            type: 'error',
            duration: 3 * 1000
          })
          return Promise.reject(new Error(response.data || 'Error'))
        }

        return response.data
      }
    },
    error => {
      console.log('err' + error) // for debug
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    }
)


export default service
